package com.kuangstudy.service.weibo;
import com.alibaba.fastjson.JSON;
import com.kuangstudy.constant.RedisConstants;
import com.kuangstudy.entity.Product;
import com.kuangstudy.entity.Weibo;
import com.kuangstudy.result.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2021/5/23 17:41
 */
@Service
@Log4j2
public class WeiBoRandomListService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 数据热加载
     */
    @PostConstruct
    public void initData() {
        log.info("将需要随机显示的榜单信息放入到redis集合中...");
        boolean flag = this.redisTemplate.hasKey(RedisConstants.WEIBO_RANDOM_SET_KEY);
        if (!flag) {
            List<Weibo> initDataList = initDataList();
            initDataList.forEach(weibo -> this.redisTemplate.opsForSet().add(RedisConstants.WEIBO_RANDOM_SET_KEY, JSON.toJSONString(weibo)));
        }
    }


    /**
     * 将需要随机的用户用户数据加载到集合中
     * 初始化100个用户，用于随机获取和推荐
     *
     * @return
     */
    private List<Weibo> initDataList() {
        List<Weibo> listdata = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            Weibo weibo = new Weibo();
            weibo.setName("榜单" + i);
            List<Map<String, Object>> mapList = new ArrayList<>();
            for (int j = 1; j <= 10; j++) {
                Map<String, Object> map = new HashMap<>();
                map.put("title", "榜单" + i + "的数据");
                mapList.add(map);
            }
            weibo.setDatas(mapList);
            listdata.add(weibo);
        }
        return listdata;
    }

    /**
     * 微博榜单换一换
     * @return
     */
    public List<Weibo> randomDataWeibo() {
        try {
            // 1: 随机获取指定num数量的用户出来
            List<String> weiboJson = (List<String>)this.redisTemplate.opsForSet().randomMembers(RedisConstants.WEIBO_RANDOM_SET_KEY,1);
            List<Weibo> weiboList = weiboJson.stream().map(s -> JSON.parseObject(s, Weibo.class)).collect(Collectors.toList());
            return weiboList;
        } catch (Exception ex) {
           throw new RuntimeException("服务器忙...");
        }
    }

}